package com.anuo.app.modules.study.studyjobschedular;

import java.util.concurrent.*;

/**
 * 研究状态: 常用已掌握
 * @ 定时执行
 * @ Timer vs ScheduledExecutorService 一般用后者, 后者是前者的替代 见下链接
 *      参考: https://stackoverflow.com/questions/409932/java-timer-vs-executorservice
 * 参考: http://tutorials.jenkov.com/java-util-concurrent/scheduledexecutorservice.html
 */
public class StudyScheduledExecutor {
    public static void main(String[] args) {
        //scheduleExecute();
        scheduleRepeatExecute();
    }

    /**
     * 定时重复执行
     * 参考: http://www.journaldev.com/2340/java-scheduler-scheduledexecutorservice-scheduledthreadpoolexecutor-example
     */
    public static void scheduleRepeatExecute(){
        int threadNumber=Runtime.getRuntime().availableProcessors()*2;
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(threadNumber);
        Runnable worker=()->{
            System.out.println("搬砖");
        };
        //每两秒执行一次
        executorService.scheduleAtFixedRate(worker, 0, 2, TimeUnit.SECONDS);
        //executorService.shutdown();//要结束这个Scheduler ,调用此代码
    }

    /**
     * 只执行一次
     */
    public static void scheduleExecute() {
        int threadNumber = Runtime.getRuntime().availableProcessors() * 2;
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(threadNumber);
        ScheduledFuture scheduledFuture = scheduledExecutorService.schedule(new Callable() {
            @Override
            public Object call() throws Exception {
                System.out.println("executed!");
                return "hello";
            }

        }, 5, TimeUnit.SECONDS);

        try {
            System.out.println("result="+scheduledFuture.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }finally {
            scheduledExecutorService.shutdown();
        }


    }
}
